<template>
    <div class="dropdown" ref="dropdownRef">
        <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="toggleOpen">
            {{title}}
        </a>
        <ul class="dropdown-menu" :style="{display:'block'}" v-if="isOpen">
            <slot></slot>
        </ul>
    </div>
</template>

<script lang="ts">
import { defineComponent ,ref,onMounted,onUnmounted,watch} from 'vue'
import useClickOutside from '../hooks/useClickOutside'
export default defineComponent({
   name:'Dropdown',
   props:{
       title:{
           type:String,
           required:true
       }
   },
   setup(){
       const isOpen = ref(false)    //用来管理菜单项的关闭与开启
       const dropdownRef=ref(null)  //取到HTMLElement元素
       const toggleOpen = () =>{    //点击 '你好 xxx' ,使菜单项开启或关闭
           isOpen.value = !isOpen.value
       }
       const isClickOutside = useClickOutside(dropdownRef)
       watch(isClickOutside,()=>{
           if(isOpen.value && isClickOutside.value){
               isOpen.value = false;
           }
       })
       return {
           isOpen,
           toggleOpen,
           dropdownRef
       }
   }
})
</script>
